package com.wxpay.util;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.jdom.JDOMException;

import com.system.property.WXProperty;
import com.system.util.PageData;

/**
 * 微信支付工具类
 * @Function 
 * @Author zhaozhenhua
 * @Date 2018年5月10日
 */
public class WXPayUtil {
	
	/**
	 * 微信支付统一下单
	  * @Description
	  * @Author zhaozhenhua
	  * @date   2018年5月10日
	  * @param pd(ORDERNUMBER,ORDERMONEY,spbillCreateIp,ORDERTYPE)
	  * @return
	 * @throws IOException 
	 * @throws JDOMException 
	  * @throws Exception
	 */
	public synchronized static SortedMap<String, Object> weixinPrePay (PageData pd) throws JDOMException, IOException{
		Map<String,String> returnMap = new HashMap<>();
			String trade_no = (String) pd.get("ORDERNUMBER");
			//支付金额
			BigDecimal totalAmount =  new BigDecimal((String)pd.get("ORDERMONEY"));
			//描述（以商品标题做为描述）
			String description = "荣耀黑卡+订单号："+trade_no;
			//预支付
			SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();  
	         parameterMap.put("appid", WXProperty.get("APP_ID"));  
	         parameterMap.put("mch_id", WXProperty.get("MCH_ID"));  
	         parameterMap.put("nonce_str", PayCommonUtil.getRandomString(32));  
	         parameterMap.put("body", description);
	         parameterMap.put("out_trade_no", trade_no);
	         parameterMap.put("fee_type", "CNY");  
	         BigDecimal total = totalAmount.multiply(new BigDecimal(100));  
	         //parameterMap.put("total_fee", total.intValue()+"");  
	         parameterMap.put("total_fee", 1+"");  
	         parameterMap.put("spbill_create_ip", pd.get("spbillCreateIp"));  
	         parameterMap.put("notify_url", WXProperty.get("notify_url"));
	         parameterMap.put("trade_type", "APP");
	         parameterMap.put("sign_type", "MD5");
	         parameterMap.put("attach", pd.get("ORDERTYPE"));//附加数据
	         String sign = PayCommonUtil.createSign("UTF-8", parameterMap) ;
	         parameterMap.put("sign", sign);
	         
	         String requestXML = PayCommonUtil.getRequestXml(parameterMap);
	         
	         System.out.println("【转换为xml格式的参数】   "+requestXML);  
	         String resultXML = PayCommonUtil.httpsRequest(  
	        		 "https://api.mch.weixin.qq.com/pay/unifiedorder","POST", requestXML); 
	         
	         System.out.println("【返回的XML】 " + resultXML);
	         Map mapResult = PayCommonUtil.doXMLParse(resultXML);
			String returnCode = (String) mapResult.get("return_code");
	         System.out.println("【返回内容   】   "+returnCode);  
	        if("SUCCESS".equals(returnCode)){
				String resultCode = (String) mapResult.get("result_code");
				if("SUCCESS".equals(resultCode)){
					String prepay_id = (String) mapResult.get("prepay_id");
					
					SortedMap<String, Object> finalpackage = new TreeMap<String, Object>();
					finalpackage.put("appid", WXProperty.get("APP_ID"));
					finalpackage.put("partnerid", WXProperty.get("MCH_ID"));
					finalpackage.put("prepayid", prepay_id);
					String noncestr = PayCommonUtil.getRandomString(32);
					finalpackage.put("noncestr", noncestr);
					String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
					finalpackage.put("timestamp", timestamp);
					finalpackage.put("package", "Sign=WXPay");
				    sign = PayCommonUtil.createSign("UTF-8", finalpackage) ;
				    SortedMap<String, Object> returnmap = new TreeMap<String, Object>();
				    returnmap.put("appid", WXProperty.get("APP_ID"));
				    returnmap.put("partnerId", WXProperty.get("MCH_ID"));
				    returnmap.put("prepayId", prepay_id);
				    returnmap.put("nonceStr", noncestr);
				    returnmap.put("timeStamp", timestamp);
				    returnmap.put("package", "Sign=WXPay");
				    returnmap.put("sign", sign);
					return returnmap;
				}else{
					String errCodeDes = (String) mapResult.get("err_code_des");
					returnMap.put("errCodeDes", errCodeDes);
				}
			}else{
				String returnMsg = (String) mapResult.get("return_msg");
				returnMap.put("returnMsg", returnMsg);
			}
			return null;
	}
	
	
	/**
     * @Author: HONGLINCHEN
     * @Description:微信退款
     * @param out_trade_no
     * @param total_fee
     * @Date: 2017-9-11 14:35
     * @return:
     */
    public static String wxPayRefund(String out_trade_no, PageData pd) {
        String requestXML = null;
        try {
            String nonceStr = PayCommonUtil.getRandomString(32);
            SortedMap<String,Object> parameters = new TreeMap<String,Object>();
            parameters.put("appid", WXProperty.get("APP_ID"));
            parameters.put("mch_id", WXProperty.get("MCH_ID"));
            parameters.put("nonce_str", nonceStr);
            parameters.put("out_trade_no", out_trade_no);   //商户订单号
            //parameters.put("transaction_id", pd.getString("ORDEROTHERNUM")); //微信订单号
            parameters.put("out_refund_no", pd.getString("REFUND_ID"));//商户退款单号
            parameters.put("fee_type", "CNY");//退款货币种类
            parameters.put("total_fee", pd.getString("ORDERMONEY"));//订单金额
            parameters.put("refund_fee", pd.getString("ORDERMONEY"));//退款金额	
            parameters.put("op_user_id", WXProperty.get("MCH_ID"));
            String sign = PayCommonUtil.createSign("UTF-8", parameters);
            parameters.put("sign", sign);
            requestXML = PayCommonUtil.getRequestXml(parameters);
            System.out.println("【转换为xml格式的参数】   "+requestXML);  
	        String resultXML = PayCommonUtil.httpsRequest(  
	        		 "https://api.mch.weixin.qq.com/secapi/pay/refund","POST", requestXML); 
	         
	         System.out.println("【返回的XML】 " + resultXML);
	         Map mapResult = PayCommonUtil.doXMLParse(resultXML);
			String returnCode = (String) mapResult.get("return_code");
	         System.out.println("【返回returnCode   】   "+returnCode);  
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        }
        return requestXML;
    }
   

}
